<template>
  <div>
    <!-- 头 -->
    <TodoHeader @addTask="addTask" :list="list" @allChecked='allChecked' />
    <!-- 列表 -->
    <TodoList :list="showList" @remove="remove" @change="edit" />
    <!-- 脚 -->
    <TodoFooter
      :list="list"
      @stateChange="stateChange"
      @removeComplete="removeComplete"
    />
  </div>
</template>

<script>
import TodoHeader from "./components/TodoHeader.vue";
import TodoList from "./components/TodoList.vue";
import TodoFooter from "./components/TodoFooter.vue";
export default {
  data() {
    return {
      list:JSON.parse(localStorage.getItem('list')||'[]'),
      // arr: [
      //   { id: 1, name: "吃饭", isDone: true },
      //   { id: 2, name: "睡觉", isDone: false },
      //   { id: 3, name: "打豆豆", isDone: true },
      // ],
      currentState: "all",
    };
  },
  // 1.监听list的变化，因为监听到isDone，所以要深度监听
  watch:{
    list:{
      handler(newVal,odlVal){
        // 保存到本地
        localStorage.setItem('list',JSON.stringify(newVal))
      },
      deep:true
    }
  },
  components: {
    TodoHeader,
    TodoList,
    TodoFooter,
  },
  computed: {
    showList() {
      switch (this.currentState) {
        case "incomplete":
          return this.list.filter((e) => !e.isDone);
        case "complete":
          return this.list.filter((e) => e.isDone);
        default:
          return this.list;
      }
    },
  },
  methods: {
    allChecked(checked){
      this.list.forEach(e=>{
        e.isDone=checked
      })
    },
    // 移除全部已完成
    removeComplete() {
      this.list = this.list.filter((e) => !e.isDone);
    },
    // 显示状态改变
    stateChange(name) {
      // if (name === "all") {
      //   this.arr = this.list;
      // } else if (name === "incomplete") {
      //   this.arr = this.list.filter((e) => !e.isDone);
      // } else if (name === "complete") {
      //   this.arr = this.list.filter((e) => e.isDone);
      // }
      this.currentState = name;
    },
    // 添加
    addTask(name) {
      const task = {
        id: this.list.length>0?this.list[this.list.length-1].id+1:1,
        name,
        isDone: false,
      };
      this.list.push(task);
    },
    // 修改
    edit(id) {
      const findRes = this.list.find((e) => e.id === id);
      if (!!findRes) {
        findRes.isDone = !findRes.isDone;
      }
    },
    // 删除
    remove(id) {
      this.list = this.list.filter((e) => e.id !== id);
    },
  },
};
</script>

<style lang='less' scoped>
</style>